import { useGlobalStore } from '@/store/global';

export default () => {
  const globalStore = useGlobalStore();

  const getFilteredTableDataByDate = (
    tableData: any[] = [],
    startDate: { getTime: () => number; getTimezoneOffset: () => number },
    endDate: { getTime: () => number; getTimezoneOffset: () => number },
    propertyKey = 'date',
  ) => {
    if (!startDate && !endDate) return tableData;
    let startDateInMs = startDate ? startDate.getTime() : 0;
    let endDateInMs = endDate ? endDate.getTime() : Number.POSITIVE_INFINITY;

    const isUtcDisplay = globalStore.isUtcDisplay;

    //Offset preference selected
    if (!isUtcDisplay) {
      startDateInMs = startDate
        ? startDate.getTime() + startDate.getTimezoneOffset() * 60000
        : 0;
      endDateInMs = endDate
        ? endDate.getTime() + endDate.getTimezoneOffset() * 60000
        : Number.POSITIVE_INFINITY;
    }

    return tableData.filter((row: { [x: string]: any }) => {
      const date = row[propertyKey];
      if (!(date instanceof Date)) return;
      const dateInMs = date.getTime();
      if (dateInMs >= startDateInMs && dateInMs <= endDateInMs) return row;
    });
  };
  return {
    getFilteredTableDataByDate,
  };
};
